<?php

namespace zhtfrontend\models\datas;


use common\components\helpers\Fun;
use Yii;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\base\Model;
use yii\helpers\Html;

/**
 * This is the model class for table "{{%teacher}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $site_id
 * @property integer $mechanic_id
 * @property string $description
 * @property string $info
 * @property integer $sex
 * @property integer $age
 * @property string $address
 * @property string $lat
 * @property string $lng
 * @property string $mobile
 * @property string $area
 * @property integer $isrecommend
 * @property integer $status
 * @property integer $created_at
 * @property integer $apply_time
 * @property integer $updated_at
 * @property integer $recommendview
 * @property string $email
 * @property integer $is_headmaster
 * @property integer $headmaster_account
 * @property integer $parent_id
 * @property integer $cate_id
 */
class Teacher extends \zhtfrontend\components\bases\BaseModel
{
    public $teach_cate;
    public $teach_cates;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%teacher}}';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'mechanic_id', 'sex', 'address', 'mobile','is_tutor','cate_id'], 'required'],
            ['mobile', 'match', 'pattern' => '/^1[0-9]{10}$/', 'message' => '手机号码格式错误'],
            [['email'], 'email'],
            [['mechanic_id', 'sex', 'age', 'isrecommend', 'status', 'created_at', 'apply_time', 'updated_at', 'is_teaching_art','is_tutor','menu_id','cate_id'], 'integer'],
            [['description'], 'string'],
            ['name', 'string', 'max' => 50],
            [['img'], 'string', 'max' => 255],
            [['address'], 'string', 'max' => 128],
            [['mobile'], 'unique'],
            ['age', 'compare', 'compareValue' => 0, 'operator' => '>='],
            ['age', 'check_age','on'=>['create']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', 'ID'),
            'name' => Yii::t('zhtfrontend', '老师姓名'),
            'img' => Yii::t('zhtfrontend', '老师头像'),
            'site_id' => Yii::t('zhtfrontend', '分店ID'),
            'mechanic_id' => Yii::t('zhtfrontend', '所属机构'),
            'sex' => Yii::t('zhtfrontend', '性别'), //0女1男
            'age' => Yii::t('zhtfrontend', '出生年份'),
            'address' => Yii::t('zhtfrontend', '地址'),
            'mobile' => Yii::t('zhtfrontend', '手机号'),
            'email' => Yii::t('zhtfrontend', '邮箱'),
            'area' => Yii::t('zhtfrontend', '区域'),
            'isrecommend' => Yii::t('zhtfrontend', '推荐'), //0,不推荐|1，推荐
            'status' => Yii::t('zhtfrontend', '状态'), //是否通过审核，0为未审核
            'created_at' => Yii::t('zhtfrontend', '创建时间'),
            'apply_time' => Yii::t('zhtfrontend', '申请时间'),
            'updated_at' => Yii::t('zhtfrontend', 'Update Time'),
            'is_headmaster' => Yii::t('zhtfrontend', '是否班主任'),
            'headmaster_account' => Yii::t('zhtfrontend', '账号'),
            'parent_id' => Yii::t('zhtfrontend', '所属班主任'),
            'cate_id' => Yii::t('zhtfrontend', '三大类'),
            'teach_cate' => Yii::t('zhtfrontend', '授课分类'),
            'teach_cates' => Yii::t('zhtfrontend', '已选授课分类'),
            'is_teaching_art' => Yii::t('zhtfrontend', '是否授课艺教学'),
            'is_tutor' => Yii::t('zhtfrontend', '是否是导师'),
            'menu_id' => Yii::t('zhtfrontend', '绑定模块'),
            'description' => Yii::t('zhtfrontend', '简介')
        ];
    }


    public function extraFields()
    {
        return [
            'mechanic_name' => function () {
                return ($this->mechanic != null) ? $this->mechanic->name : '';
            },
            'deleteHandle' => function ($data) {
                $teacher_id = Arrangement::find()->select('teacher_id')->where("teacher_id!=''")->andWhere(['is_delete' => 0])->distinct('teacher_id')->column();
                $goods = GoodsAttr::find()->where(['dmd_goodsattr.*'])->joinWith('goods')->where(['value' => $data['id'], 'obj_type' => 'teacher'])->all();
                if (($teacher_id != null && in_array($data['id'], $teacher_id) || $goods != null)) {
                    return '<button class="yx-btn-disabled1" type="button" disabled>删除</button>';
                } else {
                    return Html::a('删除', 'javascript:;', ['rel' => 'record_item_confirm', 'class' => 'btn yx-class-about yx-bga0a0a0 yx-radius2', 'data' => ['message' => '确定要删除' . $data['name'] . '吗？', 'url' => Fun::url(['teacher/delete', 'id' => $data['id']])]]);
                }

            },
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['status'] = function () {
            switch ($this->status) {
                case 0:
                    return \Yii::t('zhtfrontend', '不授课');
                case 1:
                    return \Yii::t('zhtfrontend', '授课');
            }
        };
        $fields['sex'] = function () {
            switch ($this->sex) {
                case 0:
                    return \Yii::t('zhtfrontend', '女');
                case 1:
                    return \Yii::t('zhtfrontend', '男');
            }
        };
        return $fields;
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'apply_time', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],

        ]);
    }


    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $model = new Admin();
            $model->username = $this->mobile . '_t';
            $model->email = $this->email;
            $model->mechanic_id = $this->mechanic_id;
            $model->name = $this->name;
            $model->mobile = strlen($this->mobile) == 11 ? $this->mobile : '';
            $model->role = 'teache_teacher';
            $model->teacher_id = $this->id;
            $model->created_at = $this->created_at;
            $model->logo = $this->img;
            $model->password = \Yii::$app->security->generatePasswordHash($this->mobile);
            if ($model->save(false)) {
                $auth = \Yii::$app->authManager;
                $auth->assign($auth->getRole($model->role), $model->id);
            }
        }
        else {
            $model = Admin::findOne(['role' => 'teache_teacher', 'teacher_id' => $this->id, 'mechanic_id' => $this->mechanic_id]);
            $admin = Admin::findOne(['username' => $this->mobile . '_t']);
            if(empty($admin)){
                $model->username = $this->mobile.'_t';
                $model->password = \Yii::$app->security->generatePasswordHash($this->mobile);
                $model->save(false);
            }
        }
    }

    public function check_age($attribute){
        if(strlen($this->$attribute)>4 || strlen($this->$attribute)<4){
            $this->addError($attribute, Yii::t('common', '请输入正确的年份'));
        }

    }

    public function afterDelete()
    {
        parent::afterDelete();
        $adminModel = Admin::find()->where(['teacher_id' => $this->id, 'role' => 'teache_teacher'])->one();
        if ($adminModel) {
            $adminModel->delete();
        }
    }

    public function getMechanic()
    {
        return $this->hasOne(Mechanic::className(), ['id' => 'mechanic_id']);
    }
}
